<?xml version="1.0" encoding="UTF-8"?>
<html>
    <head>
        <link type="text/css" rel="stylesheet" href="./css/template.css" />
        <link type="text/css" rel="stylesheet" href="./css/SyntaxHighlighter.css" />
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Objet ThreadLocal</title>
        <script language="javascript" src="./js/shInit.js" />
        <script language="javascript" src="./js/shCore.js" />
        <script language="javascript" src="./js/shBrushCpp.js" />
        <script language="javascript" src="./js/shBrushCSharp.js" />
        <script language="javascript" src="./js/shBrushCss.js" />
        <script language="javascript" src="./js/shBrushDelphi.js" />
        <script language="javascript" src="./js/shBrushJava.js" />
        <script language="javascript" src="./js/shBrushJScript.js" />
        <script language="javascript" src="./js/shBrushPhp.js" />
        <script language="javascript" src="./js/shBrushPython.js" />
        <script language="javascript" src="./js/shBrushRuby.js" />
        <script language="javascript" src="./js/shBrushSql.js" />
        <script language="javascript" src="./js/shBrushVb.js" />
        <script language="javascript" src="./js/shBrushXml.js" />
        <keywords>Objet ThreadLocal</keywords>
        <author>Michel PIRES</author>
    </head>
    <body>
        <div class="chapter">
            <h2>Objet ThreadLocal</h2>
        </div>
        <div class="chapter">
            <h2>1. Introduction</h2>
            <p>At the end of the year 1998, Sun launched JDK 1.2. It brought a lot of new things, and one of these new things is particulary interesting : ThreadLocal class.</p>
			<p>This class is very useful to simplify the competitive development of multi-thread programs.</p>
            <p>To illustrate that, imagine that you want to create a multi-thread application using the same instance. By using a static field, this one could be re-used in all processes, but could not be modified. By using a non-static field, this one could be modified in any process, but it isn't a good idea.</p>
            <p>For that, ThreadLocal can simplify life for us, indeed it allows us to create an own variable to each Thread. The ThreadLocal object stocks a value which is accessible only by the current thread. The others threads don't have access to this object.</p>
			<h2>2. Description</h2>
            <div class="subChapter">
                <h3>2.1 General</h3>
                <h4>Constructor :</h4>
                <textarea name="code" class="java">ThreadLocal() ;</textarea>
				<p>Build a new ThreadLocal object.</p>
                <h4>Methods :</h4>
                <textarea name="code" class="java">protected Object initialValue()</textarea>
				<p>Return the initial value of the current thread for this ThreadLocal variable.</p>
                <textarea name="code" class="java">void set(Object T)</textarea>
				<p>Fix the copy of the current Thread of this ThreadLocal variable to the indicated value.</p>
                <textarea name="code" class="java">Object get()</textarea>
				<p>Return the value in the copy of the current Thread of the ThreadLocal variable.</p>
                <textarea name="code" class="java">void remove()</textarea>
				<p>Erase the value for this ThreadLocal.</p>
                <h4>Inherited methods of java.lang.Object class :</h4>
                <p>Clone(), equals(java.lang.Object), finalize(), getClass(), hashCode(), notify(), notifyAll(), toString(), wait(), wait(long), wait(long, int).</p>
            </div>
            <div class="subChapter">
                <h3>2.2. Methods' details</h3>
                <h4>protected Object initialValue()</h4>
                <p>Without an implementation of the method set(Object T), the method initialValue() is called one time maximum for each thread created since the first get().</p>
				<p>Basically, initialValue() simply returns null, but his behavior can be redefined.</p>
                <p>Example :</p>
                <textarea name="code" class="java">//We redefine the behavior of initialValue()
					class myThreadLocal extends ThreadLocal{
					protected Object initialValue() {
					return (String) "I am an initial value";
					// It returns a string
					}
					}
					class WithThreadLocal implements Runnable {
					public myThreadLocal Tl= new myThreadLocal();
					public void run() {
					System.out.println(" ThreadLocal = "+Tl.get());
					}
					}
					public class Main {
					public static void main(String[] args) {
					Thread T1 = new Thread(new WithThreadLocal());
					T1.start();
					}
					}
					//output :
					ThreadLocal = I am an initial value
					// The ThreadLocal object took the value returned by initialValue()</textarea>
                <h4>Object get()</h4>
                <p>This method returns the value inside the ThreadLocal object an.
                <p>When the first call of get() begins, if set() hasn't been invoked previously by this Thread, the method initialValue() is called in order to establish a default value.</p>
				<p>See the previous examples.</p>
                <h4>void remove()</h4>
				<p>This method allows us to erase the ThreadLocal value.</p>
				<p>If we want to get the value of this thread again, without the method set(), we will have a null object returned by the method initialValue().</p>
                <p>Example :</p>
                <textarea name="code" class="java">class WithThreadLocal implements Runnable {
					public ThreadLocal Tl= new ThreadLocal();
					public void run() {
					Tl.set("User used set()");
					System.out.println("Before Remove: ThreadLocal = "+Tl.get());
					Tl.remove();
					System.out.println("After Remove: ThreadLocal = "+Tl.get());
					}
					}
					public class Main {
					public static void main(String[] args) {
					Thread T1 = new Thread(new WithThreadLocal());
					T1.start();
					}
					}
					//Output:
					Before Remove: ThreadLocal = User used set()
					After Remove: ThreadLocal = null
					//The method remove() deleted the content of the ThreadLocal object.
					//At the moment of the impression, the call of get() returns null, because a call to initialValue,
					//non-implemented here, has been done.</textarea>
                <h4>void set(Object T)</h4>
				<p>This method allows us to fix the value kept in the ThreadLocal object.</p>
				<p>This one is bound to the current thread and only for it.</p>
                <textarea name="code" class="java">// We attribute ourselves a value to the object kept in ThreadLocal by the method set().
					class WithThreadLocal implements Runnable {
					public ThreadLocal Tl= new ThreadLocal();
					public void run() {
					Tl.set("User used set()");
					System.out.println(" ThreadLocal = "+Tl.get());
					}
					}
					public class Main {
					public static void main(String[] args) {
					Thread T1 = new Thread(new WithThreadLocal());
					T1.start();
					}
					}
					//output :
					ThreadLocal = User used set()
					// The ThreadLocal object took the value that we attributed to it.</textarea>
                <h4>Object get()</h4>
				<p>This method returns the value kept in the ThreadLocal object an.<p/>
                <p>When we call get() for the first time, and if set() hasn't been invoked previously by this Thread, the method initialValue() is called in order to establish a default value.</p>
				<p>See the precedent examples.</p>
                <h4>void remove()</h4>
                <P>This method allows to erase the ThreadLocal value.</p>
				<p>If we want to access the value of this thread again, without a set() method, we will get a null object, returned by the method initialValue().</p>
                <p>Example :</p>
                <textarea name="code" class="java">class WithThreadLocal implements Runnable {
					public ThreadLocal Tl= new ThreadLocal();
					public void run() {
					Tl.set("User used set()");
					System.out.println("Before Remove: ThreadLocal = "+Tl.get());
					Tl.remove();
					System.out.println("After Remove: ThreadLocal = "+Tl.get());
					}
					}
					public class Main {
					public static void main(String[] args) {
					Thread T1 = new Thread(new WithThreadLocal());
					T1.start();
					}
					}
					//Output:
					Before Remove: ThreadLocal = User used set()
					After Remove: ThreadLocal = null
					//The method remove() deleted the content of the ThreadLocal object.
					//At the moment of the impression, the call of get() returns null, because a call to initialValue,
					//non-implemented here, has been done.</textarea>
                <h2>3. Remark</h2>
				<p>It's also necessary to remark that the ThreadLocal exists only when the Thread is alive.
					An example will illustrate this.</p>
                <h2>4. Utilization</h2>
				<p>As often, a little example will allow us to better understand the functioning of ThreadLocal.</p>
                <p>Example 1 :</p>
                <textarea name="code" class="java">class WithThreadLocal implements Runnable {
					public ThreadLocal Tloc;
					public Object o;
					public WithThreadLocal () {  // Constructor of our WithThreadLocal
					Tloc = new ThreadLocal();
					o = new String ();
					}
					public void to_sleep(){
					try {    Thread.sleep(1000);
					} catch (InterruptedException e) {     e.printStackTrace();    }
					}
					public void run() {
					String name = Thread.currentThread().getName();
					Tloc.set("Local_"+name);  // We attribute the same value for the ThreadLocal object and
					o = "Objet_"+name;       // for the object o.
					System.out.println("Before wating ---NAME="+ name
					+"\n      ThreadLocal="+Tloc.get()
					+"      Objet="+ o);
					to_sleep();      // We put the current Thread in standby
					System.out.println("After the sleep ---NAME="+ name
					+"\n      ThreadLocal="+Tloc.get()
					+"      Objet="+ o);
					}
					}
					public class Main {
					public static void main(String[] args) {
					WithThreadLocal tl = new WithThreadLocal();
					// we create a WithThreadLocal instance;
					Thread T0 = new Thread(tl); // Creation of the Thread T1
					Thread T1 = new Thread(tl); //
					T0.start();
					T1.start();
					try {
					T0.join();
					T1.join();
					System.out.println("\n in the Main: \nThreadLocal= "+tl.Tloc.get()+ " &amp; \nObjet= " + tl.o);
					} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					}
					}
					}
					Output :
					Before waiting ---NAME=Thread-0
					ThreadLocal=Local_Thread-0      Objet=Objet_Thread-0
					Before waiting ---NAME=Thread-1
					ThreadLocal=Local_Thread-1     Objet=Objet_Thread-1
					After the sleep ---NAME=Thread-0
					ThreadLocal=Local_Thread-0      Objet=Objet_Thread-1
					After the sleep ---NAME=Thread-1
					ThreadLocal=Local_Thread-1      Objet=Objet_Thread-1
					In the Main:
					ThreadLocal= null &amp;
					Objet= Objet_Thread-1</textarea>
                <p>Look carefully at what this program returns.
					The value of the ThreadLocal object, contrary to the "simple" object, hasn't been modified during the waiting.</p>
                <p>Indeed, the ThreadLocal is exclusive to the current Thread.</p>
				<p>Contrary to the other objects, where all Threads share it between them, and have access to it.</p>
				<p>Moreover, after the execution of the Threads, the ThreadLocal value is null. It happens because the ThreadLocal exists only when they are actives.</p>
                <h2>5. Conclusion</h2>
                <p>As we saw it, this class can certainly be useful.</p>
                <p>It simplifies the programmation on the thread level, which allow us to use at the same time objects used by all threads, and exclusive objects of the current thread thanks to ThreadLocal.</p>
				<p>Game is in your hands.</p>
            </div>
        </div>
    </body>
</html>

